<template>
  <div id="wrapper" onload="init()">
    <div style="text-align: center; display: inline-block;">
      <input v-if="!usernameFlag" v-model="usernameInput" maxlength="40" style="width: 50px;">  <!-- activeUsernameInput -->

      <span v-else>
        {{ username }}
      </span>
      的
      <p class="oneline">桌面便签</p>
      <el-button icon="el-icon-edit" circle @click="saveUsername"></el-button>
    </div>
    <!-- 主体 -->
    <div id="todoBody">
      <h3 class="oneline">未完成任务项：</h3><button class="oneline" @click="addNewItem">新增任务</button>
      <div v-for="item, index in no_complete" :key="item.id">
        <template v-if="item.editable">
          <input v-model="item.title" :ref="'input' + index" @keyup.enter="onEnter(item,index)">
        </template>
        <template v-else>
          <span @click="onEdit(item, index)">{{ item.title }}</span>
        </template>
        <!-- <input v-model="item.title" :disabled="false"> -->
        <!-- <span v-else :class="{ 'line-through': item.isStriked }">{{ item.title }}</span> -->
        <!-- <button @click="itemChange(item, index)">修改</button> -->
        <button @click="itemOK(item)">完成</button>
      </div>
      <div v-if="complete.length > 0">
        <h3 class="oneline">已完成任务项（{{ complete.length }}）：</h3><br>
        <div v-for="item in complete" :key="item.id">
          <code style="color: blue;">任务名称：{{ item.title }}<br></code>
          <code v-if="item.complete_name">完成人员：{{ item.complete_name }}&nbsp;</code>
          <code v-if="item.complete_time">完成时间：{{ item.complete_time }}&nbsp;</code>
        </div>
      </div>
      <h3 v-else>近期尚无任务完成</h3>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Item from '@/components/ItemPage/Item.vue'
import AddItem from '@/components/ItemPage/AddItem.vue'
import WebSocketUtil from '@/utils/ws.js'
import IP from 'ip'

export default {
  data () {
    return {
      complete: [],
      no_complete: [],
      ws: null,
      connected: false,
      status: '',
      msg: '',
      usernameInput: '',
      ip: '',
      items: [],
      // editable: false,
      // disabled: false,
      isStriked: false,
      ws_data: null,
      editing: false,
      titleDisplay: ''
    }
  },

  components: {
    // Item,
    // AddItem
  },

  created () {
    this.ws = new WebSocketUtil()
    const url = 'ws://192.168.99.117:3000'

    this.ws
      .connect(url + '?name=' + this.usernameInput + '&ip=' + this.ip)
  },

  mounted () {
    this.ip = IP.address()

    this.username = localStorage.getItem('username')
    if (this.username) {
      this.ws = new WebSocketUtil()
      const url = 'ws://192.168.99.117:3000'

      this.ws
        .connect(url + '?name=' + this.usernameInput + '&ip=' + this.ip)
        .then(() => {
          this.connected = true
          this.status = 'Connected'
          this.ws.receiveMessage((data) => {
            this.complete = JSON.parse(data).data.complete
            this.no_complete = JSON.parse(data).data.no_complete
            // console.log(this.msg.data);
          })
        })
        .catch((error) => {
          this.status = 'Connect failed: ' + error
        })
    }
  },

  computed: {
    username: {
      get () {
        return this.usernameInput
      },
      set (newVal) {
        this.usernameInput = newVal
      }
    }
  },

  methods: {

    async saveUsername () {
      this.usernameFlag = !this.usernameFlag
      const post_url = 'http://192.168.99.117:3000/users/login'

      const data = {
        username: this.usernameInput
      }

      try {
        let response = await axios.post(post_url, data)
        console.log(response)
      } catch (error) {
        console.error(error)
      }

      // this.ws = new WebSocketUtil();
      const url = 'ws://192.168.99.117:3000'

      this.ws
        .connect(url + '?name=' + this.usernameInput + '&ip=' + this.ip)
        .then(() => {
          this.connected = true
          this.status = 'Connected'
          this.ws.receiveMessage((data) => {
            this.complete = JSON.parse(data).data.complete
            this.no_complete = JSON.parse(data).data.no_complete
            // console.log(this.msg.data);
          })
        })
        .catch((error) => {
          this.status = 'Connect failed: ' + error
        })

      // 保存到localStorage
      localStorage.setItem('username', this.usernameInput)
    },

    activeUsernameInput () {
      console.log('点击了')
      this.username = ''
      localStorage.removeItem('username')
    },

    handleAddItem (item) {
      const i = {
        'type': 'add',
        'user': this.usernameInput,
        'title': ''
      }
      this.items.push(i)
      console.log('未完成：' + this.no_complete)
      console.log(item)
    },

    itemOK (item) {
      item.isStriked = !item.isStriked
      if (item.title) {
        this.ws_data = {
          'type': 'edit',
          'user': this.usernameInput,
          'title': item.title,
          'id': item.id,
          'editable': true
        }
        this.ws_data = JSON.stringify(this.ws_data)
        console.log('item的值' + this.ws_data)
        this.ws.sendMessage(this.ws_data)
        this.ws_data = {
          'type': 'complete',
          'user': this.usernameInput,
          'id': item.id
        }
        this.ws_data = JSON.stringify(this.ws_data)
        console.log(this.ws_data)
        this.ws.sendMessage(this.ws_data)
        // })
        // .catch((error) => {
        //   this.status = "Connect failed: " + error;
        //   console.log(this.status);
        // });
        console.log(this.ws_data)
        console.log('任务完成')
      } else {
        return false
      }
    },

    itemChange (item, index) {
      this.no_complete[index].editable = !this.no_complete[index].editable
      this.ws_data = {
        'type': 'edit',
        'user': this.usernameInput,
        'title': item.title,
        'id': item.id,
        'editable': true
      }
      this.ws_data = JSON.stringify(this.ws_data)
      console.log('item的值' + this.ws_data)
      this.ws.sendMessage(this.ws_data)
    },

    addNewItem () {
      this.ws_data = {
        'type': 'add',
        'user': this.usernameInput,
        'title': '《新增任务，点击修改》'
      }
      this.ws_data = JSON.stringify(this.ws_data)
      console.log('addNewItem' + this.ws_data)
      this.ws.sendMessage(this.ws_data)
    },

    onEdit (item, index) {
      // this.editing = true;
      let new_no_complete = this.no_complete
      // console.log('onedit:')
      // console.log(new_no_complete[0].editable)
      // console.log(item.editable)
      console.log(index)
      new_no_complete[index].editable = !new_no_complete[index].editable
      let editable = new_no_complete[index].editable
      this.no_complete = new_no_complete
      console.log(editable)
      this.$nextTick(() => {
        this.$refs['input' + index][0].focus()
      })
      // if(!editable){
      //   this.ws_data = {
      //     'type': 'edit',
      //     'user': this.usernameInput,
      //     'title': item.title,
      //     'id': item.id,
      //     'editable': true
      //   }
      //   this.ws_data = JSON.stringify(this.ws_data)
      //   console.log("item的值" + this.ws_data);
      //   this.ws.sendMessage(this.ws_data);
      //   this.$nextTick(() => {
      //     this.$refs.input.focus();
      //   });
      // }else{
      //   // this.no_complete[index].editable = !item.editable
      //   // new_no_complete[index].editable = !item.editable
      //   // this.no_complete = new_no_complete
      // }
    },
    onEnter (item, index) {
      // this.editing = false;
      // this.itemChange(item, index)
      let new_no_complete = this.no_complete
      new_no_complete[index].editable = !new_no_complete[index].editable
      let editable = new_no_complete[index].editable
      this.no_complete = new_no_complete
      console.log(editable)
      this.ws_data = {
        'type': 'edit',
        'user': this.usernameInput,
        'title': item.title,
        'id': item.id,
        'editable': true
      }
      this.ws_data = JSON.stringify(this.ws_data)
      console.log('item的值' + this.ws_data)
      this.ws.sendMessage(this.ws_data)
    }
  }
}

</script>

<style>
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro');

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Source Sans Pro', sans-serif;
  background-color: antiquewhite;
  margin: 0;
  overflow: auto;
}

button {}

.oneline {
  display: inline-block;
}

input {}

code {
  color: red;
}
</style>
